package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.IProofCameroonContactListener
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.IProofCameroonDateListener
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.IProofCameroonDatePickerListener
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.IProofCameroonSelectListener
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.ProofCameroonContact
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.ProofCameroonDate
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.ProofCameroonDatePicker
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.ProofCameroonInput
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.subview.ProofCameroonSelect
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonProofBinding
import org.json.JSONObject

class ProofCameroonActivity : AppCompatActivity() {

    private lateinit var proofViewModel: ProofCameroonViewModel
    private lateinit var binding: ActivityCameroonProofBinding
    private lateinit var adapter: ProofCameroonPageAdapter
    private lateinit var datePick: ProofCameroonDatePicker

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        proofViewModel = ViewModelProvider(this)[ProofCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonProofBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val title = binding.navbarTitle
        val back = binding.navbarLeft
        val save = binding.save
        val list = binding.list
        val loading = binding.loading
        val header = binding.header

        // 初始化日期组件
        datePick = ProofCameroonDatePicker(object : IProofCameroonDatePickerListener {
            override fun onClick(date: String, pickTag: String) {
                proofViewModel.selectedDate(date = date, tid = pickTag)
            }
        })

        // 初始化adapter
        adapter = ProofCameroonPageAdapter(emptyList(), object : IProofCameroonPageListener {
            override fun onClick(tid: String, isDate: Boolean) {
                if (isDate) {
                    datePick.setPickType(pickTag = tid)
                    datePick.showNow(supportFragmentManager, tid)
                }
            }
        })
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 页面loading状态接口监听
        proofViewModel.loadingResult.observe(this@ProofCameroonActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        proofViewModel.pageDetailResult.observe(this@ProofCameroonActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                // TODO: 失败
                showMessage(pageDetailResult.error)
                return@Observer
            }
            if (pageDetailResult.headers != null) {
                header.setDataList(pageDetailResult.headers)
            }
            if (pageDetailResult.items != null) {
                title.text = pageDetailResult.pageTitle
                adapter.dataList = pageDetailResult.items
                adapter.notifyDataSetChanged()
            }
            val barTitle = title.text.toString()
            val stepFlag = pageDetailResult.step ?: barTitle
            hitPointCameroon(type = "PROOF_${stepFlag}_CAMEROONACTIVITY", remark = barTitle, isPageStart = true)
        })

        // 保存接口监听
        proofViewModel.saveStepResult.observe(this@ProofCameroonActivity, Observer {
            val saveStepResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (saveStepResult.error != null) {
                // TODO: 失败
                showMessage(saveStepResult.error)
                return@Observer
            }
        })

        // 流程接口监听
        proofViewModel.mainProcessResult.observe(this@ProofCameroonActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                proofViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        proofViewModel.nextRouterResult.observe(this@ProofCameroonActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击保存
        save.setOnClickListener {
            loading.visibility = View.VISIBLE
            proofViewModel.saveStepInfo()

            val stepFlag = proofViewModel.pageDetailResult.value?.step ?: title.text.toString()
            hitPointCameroon("PROOF_SAVE_${stepFlag}_COMMIT", title.text.toString())
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 查询页面详情
        proofViewModel.pageDetail()
    }


    private fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap()
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
            finish()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
//        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)

        val barTitle = binding.navbarTitle.text.toString()
        val stepFlag = proofViewModel.pageDetailResult.value?.step ?: barTitle
        hitPointCameroon(type = "PROOF_${stepFlag}", remark = barTitle, isPageEnd = true)
    }
}

interface IProofCameroonPageListener {
    fun onClick(tid: String, isDate: Boolean = false)
}

class ProofCameroonPageAdapter(
    var dataList: List<JSONObject>,
    var onItemClick: IProofCameroonPageListener? = null
) :
    RecyclerView.Adapter<ProofCameroonPageAdapter.ViewHolder>() {

    val ViewType_Input: Int = 0
    val ViewType_Select: Int = 1
    val ViewType_Date: Int = 2
    val ViewType_Contact: Int = 3

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        if (ViewType_Input == viewType) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.view_cameroon_proof_activity_adapter_input, parent, false)
            return ViewHolder(view, viewType)

        } else if (ViewType_Select == viewType) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.view_cameroon_proof_activity_adapter_select, parent, false)
            return ViewHolder(view, viewType)

        } else if (ViewType_Date == viewType) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.view_cameroon_proof_activity_adapter_date, parent, false)
            return ViewHolder(view, viewType)

        } else if (ViewType_Contact == viewType) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.view_cameroon_proof_activity_adapter_contact, parent, false)
            return ViewHolder(view, viewType)

        } else {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.view_cameroon_proof_activity_adapter_input, parent, false)
            return ViewHolder(view, viewType)
        }
    }

    inner class ViewHolder(view: View, viewType: Int) : RecyclerView.ViewHolder(view) {
        var input: ProofCameroonInput? = null
        var select: ProofCameroonSelect? = null
        var date: ProofCameroonDate? = null
        var contact: ProofCameroonContact? = null

        init {
            if (ViewType_Input == viewType) {
                input = view.findViewById(R.id.input)

            } else if (ViewType_Select == viewType) {
                select = view.findViewById(R.id.select)

            } else if (ViewType_Date == viewType) {
                date = view.findViewById(R.id.date)

            } else if (ViewType_Contact == viewType) {
                contact = view.findViewById(R.id.contact)
            }
        }

        fun bindData(item: JSONObject) {
            input?.setBindData(item)
            select?.setBindData(item, object : IProofCameroonSelectListener {
                override fun onClick(tid: String) {
                    onItemClick?.onClick(tid = tid)
                }
            })
            date?.setBindData(item, object : IProofCameroonDateListener {
                override fun onClick(tid: String) {
                    onItemClick?.onClick(tid = tid, isDate = true)
                }
            })
            contact?.setBindData(item, object : IProofCameroonContactListener {
                override fun onClick(tid: String) {
                    onItemClick?.onClick(tid = tid)
                }
            })
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun getItemViewType(position: Int): Int {
        val data: JSONObject = dataList[position]
        return data.optInt("viewType", 0)
    }
}